package net.caixiaomi.info.Lottery.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sobot.chat.utils.ScreenUtils;

import net.caixiaomi.info.Lottery.callback.LotteryMainCallBack;
import net.caixiaomi.info.Lottery.fragment.CourageDragFragment;
import net.caixiaomi.info.Lottery.fragment.StandardSelectFragment;
import net.caixiaomi.info.Lottery.model.LotteryBettingEntity;
import net.caixiaomi.info.Lottery.model.LotteryTicketInfo;
import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.util.Constants;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by suntian on 2018/7/31.
 */

public class BallLotteryMainActivity extends BaseActivity implements LotteryMainCallBack {

    private boolean mControl=false;
    private boolean mStandardCorrect=false;   //标准是否可以投注
    private boolean mCourageCorrect=false;   //胆拖是否可以投注
    private StandardSelectFragment mStandardFragment;
    private CourageDragFragment mCourageDragFragment;
    private FragmentManager manager;
    private int mCurrentPosition;   //当前页面

    private View mSelectView;
    private View mMoreView;
    private PopupWindow mSelectPopup;
    private PopupWindow mMorePopup;

    private ImageView mSelectArrow;
    private LinearLayout mSelectGroup;
    private TextView mTotalDesTv;

    private RelativeLayout mLeftLayout;
    private RelativeLayout mRightLayout;
    private TextView mLeftTv;
    private TextView mRightTv;
    private ImageView mLeftImg;
    private ImageView mRightImg;
    private ImageView mDeleteImg;
    private RelativeLayout mConfirmBtn;

    private TextView mMoreMissTv;

    private Context mContext;

    private SensorManager sensorManager;
    private Vibrator vibrator;
    private ShakeListener shakeListener;
    public static final int BALL_BEFORE=0;
    public static final int BALL_AFTER=1;
    public static final int BALL_BEFORE_DAN=2;
    public static final int BALL_BEFORE_TUO=3;
    public static final int BALL_AFTER_DAN=4;
    public static final int BALL_AFTER_TUO=5;

    private String mStandardDes="<html><body>请至少选择<font color='red'>5</font>个红球 <font color='blue'>2</font>个蓝球 </body></html>";
    private String mCourageDragDes="<html><body>请至少选择<font color='red'>6</font>个红球 <font color='blue'>2</font>个蓝球 </body></html>";

    private String mAppTitle;

    @Override
    protected int layout() {
        return R.layout.ball_lottery_main_layout;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
//        mAppTitle=getString(R.string.app_name)+" · ";
        mAppTitle="";
        //----------摇一摇
        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
        shakeListener = new ShakeListener();
        //----------

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        mSelectView=View.inflate(this,R.layout.lottery_select_layout,null);
        mLeftLayout=mSelectView.findViewById(R.id.select_lottery_left);
        mLeftLayout.setOnClickListener(pupopCLick);
        mRightLayout=mSelectView.findViewById(R.id.select_lottery_right);
        mRightLayout.setOnClickListener(pupopCLick);
        mLeftTv=mSelectView.findViewById(R.id.select_lottery_left_tv);
        mLeftImg=mSelectView.findViewById(R.id.select_lottery_left_img);
        mRightTv=mSelectView.findViewById(R.id.select_lottery_right_tv);
        mRightImg=mSelectView.findViewById(R.id.select_lottery_right_img);

        mMoreView=View.inflate(this,R.layout.lottery_more_layout,null);
        mMoreMissTv=mMoreView.findViewById(R.id.lottery_more_tv_3);
        mMoreView.findViewById(R.id.lottery_more0).setOnClickListener(pupopCLick);
        mMoreView.findViewById(R.id.lottery_more1).setOnClickListener(pupopCLick);
        mMoreView.findViewById(R.id.lottery_more2).setOnClickListener(pupopCLick);
        mMoreView.findViewById(R.id.lottery_more3).setOnClickListener(pupopCLick);

        mTotalDesTv= (TextView) findViewById(R.id.ball_total_des);

        mConfirmBtn= (RelativeLayout) findViewById(R.id.ball_lottery_confirm);
        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mCurrentPosition==0){
                    if(mStandardCorrect){
                        mStandardFragment.addBetingData();
                        Intent intent=new Intent(mContext,LotteryBettingConfirmActivity.class);
                        intent.putExtra("type",0);
                        mContext.startActivity(intent);
                        finish();
                    }
                }else{
                    if(mCourageCorrect){
                        boolean success=mCourageDragFragment.addBetingData();
                        if(!success){
                            return;
                        }
                        Intent intent=new Intent(mContext,LotteryBettingConfirmActivity.class);
                        intent.putExtra("type",1);
                        mContext.startActivity(intent);
                        finish();
                    }
                }

            }
        });

        manager=getSupportFragmentManager();
//        setSelection(0);

        mSelectArrow= (ImageView) findViewById(R.id.lottery_select_arrow);
        mSelectGroup= (LinearLayout) findViewById(R.id.lottery_select_group);
        final View barView=findViewById(R.id.toolbar);
        mSelectGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showListPopupWindow(barView);
            }
        });
        findViewById(R.id.lottery_more_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMorePopupWindow(findViewById(R.id.lottery_more_iv));
            }
        });

        mDeleteImg= (ImageView) findViewById(R.id.lottery_delete_img);
        mDeleteImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(mCurrentPosition==0){
                    if(mStandardFragment.isNoBallCheck()){
                        return;
                    }
                }else{
                    if(mCourageDragFragment.isNoBallCheck()){
                        return;
                    }
                }

                BaseAlertDialog dialog=new BaseAlertDialog(mContext);
                dialog.setTitle("温馨提示");
                dialog.setMessage("确定清空所选号码吗?");
                dialog.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(mCurrentPosition==0){
                            mStandardFragment.clearBall();
                        }else{
                            mCourageDragFragment.clearBall();
                        }
                    }
                });
                dialog.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                dialog.show();
            }
        });
        if(CommonApp.mLotteryIndex!=-1){
            LotteryBettingEntity entity=CommonApp.mLotteryBettingList.get(CommonApp.mLotteryIndex);
            if(entity.getStatus()==0||entity.getStatus()==1){
                setSelection(0);
            }else{
                setSelection(1);
            }
        }else{
            Intent intent=getIntent();
            int type=intent.getIntExtra("type",-1);
            if(type==1){
                setSelection(1);
            }else{
                setSelection(0);
            }
        }
//        mStandardFragment.setNumMissControl(mControl);
        mMoreMissTv.setText(mControl?"隐藏遗漏":"显示遗漏");
    }

    @Override
    public void getkTotalDes(String des,boolean correct) {
        if(mCurrentPosition==0){
            mStandardDes=des;
            mStandardCorrect=correct;
            if(mStandardCorrect){
                mConfirmBtn.setBackgroundResource(R.color.orange_primary);
            }else{
                mConfirmBtn.setBackgroundResource(R.color.divider);
            }
        }else{
            mCourageDragDes=des;
            mCourageCorrect=correct;
            if(mCourageCorrect){
                mConfirmBtn.setBackgroundResource(R.color.orange_primary);
            }else{
                mConfirmBtn.setBackgroundResource(R.color.divider);
            }
        }
        mTotalDesTv.setText(Html.fromHtml(des));
    }

    @Override
    public void getLottertInfo(LotteryTicketInfo info) {
        if(mCurrentPosition==0){
            mStandardFragment.setInfo(info);
        }else{
            mCourageDragFragment.setInfo(info);
        }
    }

    public void setSelection(int position) {
        mCurrentPosition = position;
        FragmentTransaction transaction = manager.beginTransaction();
        hideFragments(transaction);
        switch (position){
            case 0:
                if (mStandardFragment == null) {
                    mStandardFragment = new StandardSelectFragment();
                    transaction.add(R.id.fragment, mStandardFragment);
                    mStandardFragment.setCallBack(this);
                    mStandardFragment.setNumMissControl(mControl);

                }
                transaction.show(mStandardFragment);
                mLeftLayout.setBackgroundResource(R.drawable.lottery_select_pre_bg);
                mRightLayout.setBackgroundResource(R.drawable.lottery_select_nor_bg);
                mLeftImg.setVisibility(View.VISIBLE);
                mRightImg.setVisibility(View.GONE);
                mLeftTv.setTextColor(getResources().getColor(R.color.orange_primary));
                mRightTv.setTextColor(getResources().getColor(R.color.primary_text));
                changeTitle(mAppTitle+"标准选号");
                //----------
                startShock();
                mTotalDesTv.setText(Html.fromHtml(mStandardDes));
                if(mStandardCorrect){
                    mConfirmBtn.setBackgroundResource(R.color.orange_primary);
                }else{
                    mConfirmBtn.setBackgroundResource(R.color.divider);
                }
//                mTotalDesTv.setText(mStandardDes);

                break;
            case 1:
                if (mCourageDragFragment == null) {
                    mCourageDragFragment = new CourageDragFragment();
                    transaction.add(R.id.fragment, mCourageDragFragment);
                    mCourageDragFragment.setCallBack(this);
                    mCourageDragFragment.setNumMissControl(mControl);
                }
                transaction.show(mCourageDragFragment);
                mRightLayout.setBackgroundResource(R.drawable.lottery_select_pre_bg);
                mLeftLayout.setBackgroundResource(R.drawable.lottery_select_nor_bg);
                mLeftImg.setVisibility(View.GONE);
                mRightImg.setVisibility(View.VISIBLE);
                mLeftTv.setTextColor(getResources().getColor(R.color.primary_text));
                mRightTv.setTextColor(getResources().getColor(R.color.orange_primary));
                changeTitle(mAppTitle+"胆拖选号");
                //--------
                sensorManager.unregisterListener(shakeListener);
//                mTotalDesTv.setText(mCourageDragDes);
                mTotalDesTv.setText(Html.fromHtml(mCourageDragDes));
                if(mCourageCorrect){
                    mConfirmBtn.setBackgroundResource(R.color.orange_primary);
                }else{
                    mConfirmBtn.setBackgroundResource(R.color.divider);
                }
                break;
        }

        transaction.commit();
    }

    private void hideFragments(FragmentTransaction transaction) {

        if (mStandardFragment != null) {
            transaction.hide(mStandardFragment);
        }
        if (mCourageDragFragment != null){
            transaction.hide(mCourageDragFragment);
        }
    }

    public void showMorePopupWindow(View view){

        if (mMorePopup == null) {
            mMorePopup = new PopupWindow(this);
        }

        mMorePopup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mMorePopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mMorePopup.setFocusable(true);
        mMorePopup.setBackgroundDrawable(new BitmapDrawable());
        if(mMorePopup.isShowing()){
            mMorePopup.dismiss();
            return;
        }

        mMorePopup.setContentView(mMoreView);

        mMorePopup.setOutsideTouchable(true);
        mMorePopup.setBackgroundDrawable(null);
        mMorePopup.showAsDropDown(view,-ScreenUtils.dip2px(this,85), ScreenUtils.dip2px(this,5));

        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().setAttributes(lp);
        mMorePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    public void showListPopupWindow(View view) {
        if (mSelectPopup == null) {
            mSelectPopup = new PopupWindow(this);
        }

        mSelectPopup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSelectPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSelectPopup.setFocusable(true);
        mSelectPopup.setBackgroundDrawable(new BitmapDrawable());
        if(mSelectPopup.isShowing()){
            mSelectPopup.dismiss();
            return;
        }

        mSelectPopup.setContentView(mSelectView);

        mSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //旋转0度是复位ImageView
                mSelectArrow.animate().setDuration(300).rotation(0).start();
//                WindowManager.LayoutParams lp = getWindow().getAttributes();
//                lp.alpha = 1f;
//                getWindow().setAttributes(lp);

                findViewById(R.id.masking).setVisibility(View.GONE);
            }
        });

        // 设置背景颜色变暗
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = 0.7f;
//        getWindow().setAttributes(lp);

        findViewById(R.id.masking).setVisibility(View.VISIBLE);

        mSelectPopup.setOutsideTouchable(true);
        mSelectPopup.setWidth(CommonApp.mScreenWidth);
        mSelectPopup.setBackgroundDrawable(null);
        mSelectPopup.showAsDropDown(view);
        mSelectArrow.animate().setDuration(300).rotation(180).start();
    }


    private View.OnClickListener pupopCLick=new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.select_lottery_left:
                    setSelection(0);
                    mSelectPopup.dismiss();
                    break;
                case R.id.select_lottery_right:
                    setSelection(1);
                    mSelectPopup.dismiss();
                    break;
                case R.id.lottery_more0:
                    Intent trend=new Intent(mContext,LotteryTrendActivity.class);
                    mContext.startActivity(trend);
                    mMorePopup.dismiss();
                    break;
                case R.id.lottery_more1:
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(Constants.BASE_H5_URL).append("daletou/playHelp");
                    String url = stringBuilder.toString();
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                    mMorePopup.dismiss();
                    break;
                case R.id.lottery_more2:
                    mMorePopup.dismiss();
                    break;
                case R.id.lottery_more3:
                    mControl=!mControl;
                    if(mStandardFragment!=null) {
                        mStandardFragment.setNumMissControl(mControl);
                    }
                    if(mCourageDragFragment!=null) {
                        mCourageDragFragment.setNumMissControl(mControl);
                    }
                    mMorePopup.dismiss();
                    mMoreMissTv.setText(mControl?"隐藏遗漏":"显示遗漏");

                    break;
            }
        }
    };

    private void startShock(){
        sensorManager.registerListener(shakeListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(shakeListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mCurrentPosition==0){
            startShock();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        sensorManager.unregisterListener(shakeListener);
    }

    //摇一摇监听器
    public class ShakeListener implements SensorEventListener {
        /**
         * 检测的时间间隔
         */
        static final int UPDATE_INTERVAL = 100;
        /**
         * 上一次检测的时间
         */
        long mLastUpdateTime;
        /**
         * 上一次检测时，加速度在x、y、z方向上的分量，用于和当前加速度比较求差。
         */
        float mLastX, mLastY, mLastZ;

        /**
         * 摇晃检测阈值，决定了对摇晃的敏感程度，越小越敏感。
         */
//        public int shakeThreshold = 2000;
        public int shakeThreshold = ScreenUtils.dip2px(mContext,500);

        @Override
        public void onSensorChanged(SensorEvent event) {
            long currentTime = System.currentTimeMillis();
            long diffTime = currentTime - mLastUpdateTime;
            if (diffTime < UPDATE_INTERVAL) {
                return;
            }
            mLastUpdateTime = currentTime;
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];
            float deltaX = x - mLastX;
            float deltaY = y - mLastY;
            float deltaZ = z - mLastZ;
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            float delta = (float) (Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / diffTime * 10000);
            // 当加速度的差值大于指定的阈值，认为这是一个摇晃
            if (delta > shakeThreshold) {
                vibrator.vibrate(200);
                mStandardFragment.setShock();   //摇一摇选号
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommonApp.mLotteryIndex=-1;
    }
}
